<?php

class Perjalanan extends CI_Controller {

    var $_public_view;

    function __construct() {
        parent::__construct();
        $this->load->model('model_perjalanan', 'mtrip');
        $this->load->helper('url');
        $this->load->library('session');
        $this->config->load('ojexcom');
        $this->_public_view = $this->config->item('public_view');
    }

    function index() {        
        
        //cek session       
        $isLogin = $this->session->userdata('isLogin');
        if($this->session->userdata('page') and $isLogin){
            $this->session->unset_userdata('page');
        } else {
            $this->session->set_userdata('page','perjalanan');
        }
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        } else {
            echo "silakan LOG IN untuk masuk atau SIGN UP untuk register";
            redirect('registrasi','refresh');
        }

        $data = array(
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_title' => 'O-JEX',
            'page_content' => 'perjalanan');
       $this->load->view($this->_public_view, $data);
     }

     function coba(){
        //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = '';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }
        $data = array(
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_title' => 'O-JEX',
            'page_content' => 'coba');
       $this->load->view($this->_public_view, $data);
     }

     function buat(){
        //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = '';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        $userid = $id;
        $data_output['success'] = "false";
        
        $set_data = array(
            'is_available' => 0,
        );  
        $this->db->where('userId', $userid);
        $this->db->update('trip', $set_data); //<-kenapa perlu update? disable semua trip milik userid?

        $source_coordinate = $this->get_coordinate($this->input->post('source_label'));
        $dest_coordinate = $this->get_coordinate($this->input->post('destination_label'));
        $input_data = array(
            'userId' => $userid,
            'source_label' => $this->input->post('source_label'),
            'source_latitude' => $source_coordinate['lat'],
            'source_longitude' => $source_coordinate['lng'],
            'destination_label' => $this->input->post('destination_label'),
            'destination_latitude' => $dest_coordinate['lat'],
            'destination_longitude' => $dest_coordinate['lng'],
            'via' => $this->input->post('via'),
            'departTime' => date('Y-m-d H:i',strtotime($this->input->post('departTime'))) ,
            'priceInRupiah' => $this->input->post('priceInRupiah'),
            'priceInPoint' => $this->input->post('priceInPoint'),
            'notes' => $this->input->post('notes'),
            'status' => $this->input->post('status'),
        );      
        $this->db->insert('trip', $input_data);
        
        $data_output['success'] = "true";
        $tripID = 0;
        $query = $this->db->query("SELECT `id` FROM `trip` WHERE userId=".$userid." ORDER BY `id` DESC LIMIT 1");
        $row = $query->row();
        $tripID = $row->id;
            
        if($this->db->affected_rows() < 1)              $data_output['success'] = "false";
        else            $data_output['id'] = "".$tripID;
        
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
        redirect('home','refresh');
     }

     function get_coordinate($address=""){
        $result = "";
        // We get the JSON results from this request
        $geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false');
        // We convert the JSON to an array
        $geo = json_decode($geo, true);
        // If everything is cool
        if ($geo['status'] = 'OK') {
            // We set our values
            $result['lat'] = $geo['results'][0]['geometry']['location']['lat'];
            $result['lng'] = $geo['results'][0]['geometry']['location']['lng'];
        }
        return $result;
     }

     function cari(){
        //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = '';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }
        $data = array(
            'isLogin' => $isLogin, 'user' => $user, 'id'=>$id,
            //'perjalanan' => $this->mtrip->get_trip(),
            'pengemudi'=>$this->mtrip->get_pengemudi(),
            'page_title' => 'O-JEX',
            'page_content' => 'cari_perjalanan');
       $this->load->view($this->_public_view, $data);
     }

     function edit(){
         //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }
        
        //cek authorisasi
        if($id != $str_id){
            echo 'Maaf, Anda tidak bisa mengakses halaman ini';
            redirect('home','refresh');
        }

        $data = array(
            //'detail' => $this->muser->get_user_trip_detail($str_id),
            'output' => $this->get($str_id),
            'page_title' => 'Update Perjalanan',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_content' => 'edit_perjalanan');
       $this->load->view($this->_public_view, $data);
    }

     function update(){        
        //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $user_id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $user_id = $this->session->userdata('user_id');
        }
        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        //cek authorisasi
        // if($user_id != $str_id){
        //     echo 'Maaf, Anda tidak bisa mengakses halaman ini';
        //     redirect('home','refresh');
        // }

        //$id = $this->input->post('idTrip');
        $id = $str_id; //echo $id;
        $input_data = array(
            'source_label' => $this->input->post('source_label'),
            'source_latitude' => $this->input->post('source_latitude'),
            'source_longitude' => $this->input->post('source_longitude'),
            'destination_label' => $this->input->post('destination_label'),
            'destination_latitude' => $this->input->post('destination_latitude'),
            'destination_longitude' => $this->input->post('destination_longitude'),
            'via' => $this->input->post('via'),
            'departTime' => date('Y-m-d H:i',strtotime($this->input->post('departTime'))) ,
            'priceInRupiah' => $this->input->post('priceInRupiah'),
            'priceInPoint' => $this->input->post('priceInPoint'),
            'notes' => $this->input->post('notes'),
            'status' => $this->input->post('status'),
        );
        $this->db->where('id', $id);
        $this->db->update('trip', $input_data); 
        if($this->db->affected_rows() < 1)              $data_output['success'] = "false";
        else            $data_output['success'] = "true";
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
        redirect('home','location');
    }
    
    function hapus(){
        //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $user_id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $user_id = $this->session->userdata('user_id');
        }
        
        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }
        //$id = $this->input->post('idTrip');

        //cek authorisasi
        if($id != $str_id){
            echo 'Maaf, Anda tidak bisa mengakses halaman ini';
            redirect('home','refresh');
        }

        $id = $str_id;
        $this->db->where('id', $id);
        $this->db->delete('trip'); 
        if($this->db->affected_rows() < 1)              $data_output['success'] = "false";
        else            $data_output['success'] = "true";
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
        redirect('home','refresh');
    }

    function get($str_id=''){

        $data_output['success'] = "false";
        $userid = $str_id;
        //$myid = $id;        
        
        $query = $this->db->query("SELECT t.* FROM trip t JOIN `user` u ON u.id=t.userId WHERE departTime >= '".date("Y-m-d H:i:s")."' AND userId = ".$userid." AND t.is_available=1 ORDER BY departTime LIMIT 1");
        if($query->num_rows() < 1){
            $data_output['currentTrip'] = "";
        }else{
            $row = $query->row(); 
            $data_output["currentTrip"][0]["id"] = $row->id;
            $data_output["currentTrip"][0]["status"] = $row->status;
            $data_output["currentTrip"][0]["source_label"] = $row->source_label;
            $data_output["currentTrip"][0]["source_latitude"] = $row->source_latitude;
            $data_output["currentTrip"][0]["source_longitude"] = $row->source_longitude;
            $data_output["currentTrip"][0]["destination_label"] = $row->destination_label;
            $data_output["currentTrip"][0]["destination_latitude"] = $row->destination_latitude;
            $data_output["currentTrip"][0]["destination_longitude"] = $row->destination_longitude;
            $data_output["currentTrip"][0]["via"] = $row->via;
            $data_output["currentTrip"][0]["priceInRupiah"] = $row->priceInRupiah;
            $data_output["currentTrip"][0]["priceInPoint"] = $row->priceInPoint;
            $data_output["currentTrip"][0]["departTime"] = $row->departTime;
            $data_output["currentTrip"][0]["notes"] = $row->notes;
            //if($row->status == 'P' && $myid != $userid)             $data_output["pickUpStatus"] = $this->getPickupStatus($myid,$userid);
        } 
         
        return $data_output;
     }
     

}

?>
